package com.dailyblue.project.smbms.alibaba.address.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.smbms.alibaba.address.mapper.AddressMapper;
import com.dailyblue.project.smbms.alibaba.address.service.AddressService;
import com.dailyblue.project.smbms.alibaba.commons.bean.Address;
import com.dailyblue.project.smbms.alibaba.commons.util.JsonResult;
import com.dailyblue.project.smbms.alibaba.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Cacheable(cacheNames = "findAddressByUserId", key = "#userId")
    public JsonResult findAddressByUserId(int userId) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        List<Address> list = list(wrapper);
        AtomicReference<Integer> defaultAddress = new AtomicReference<>(0);
        list.forEach(e -> {
            if (e.getDefaultAddress() == 1) {
                defaultAddress.set(e.getId());
            }
        });
        JsonResult result = ResultTool.success(list, defaultAddress.get() + "");
        log.info("{}", result);
        return result;
    }

    @Override
    public JsonResult findUserIdByAddressId(int id) {
        return ResultTool.success(baseMapper.findUserIdByAddressId(id));
    }

    @Override
    public Address findByAddressId(int id) {
        return baseMapper.findByAddressId(id);
    }
}
